package org.example.backend.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.example.backend.dto.LoginDTO;
import org.example.backend.dto.LoginResponseDTO;
import org.example.backend.entity.Admin;
import org.example.backend.mapper.AdminMapper;
import org.example.backend.service.AdminService;
import org.example.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 管理员服务实现类
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public LoginResponseDTO login(LoginDTO loginDTO) {
        // 根据用户名查询管理员
        Admin admin = getByUsername(loginDTO.getUsername());
        if (admin == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!BCrypt.checkpw(loginDTO.getPassword(), admin.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 验证状态
        if (admin.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }

        // 验证角色
        if (!admin.getRole().equals(loginDTO.getRole())) {
            throw new RuntimeException("角色不匹配");
        }

        // 生成token
        String token = jwtUtil.generateToken(admin.getId(), admin.getUsername(), admin.getRole());

        // 构造返回结果
        LoginResponseDTO responseDTO = new LoginResponseDTO();
        responseDTO.setUserId(admin.getId());
        responseDTO.setUsername(admin.getUsername());
        responseDTO.setRole(admin.getRole());
        responseDTO.setToken(token);
        responseDTO.setRealName(admin.getRealName());
        responseDTO.setPhone(admin.getPhone());
        responseDTO.setEmail(admin.getEmail());

        return responseDTO;
    }

    @Override
    public Page<Admin> pageAdmin(Page<Admin> page, String keyword, String role) {
        if (StringUtils.isBlank(keyword) && StringUtils.isBlank(role)) {
            return page(page);
        }
        return baseMapper.pageAdmin(page, keyword, role);
    }

    @Override
    public Admin getByUsername(String username) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, username);
        return getOne(wrapper);
    }
} 